from rest_framework import generics, permissions
from .models import Dish
from .serializers import DishSerializer, DishCreateUpdateSerializer
from .permissions import IsDishOwnerOrReadOnly

class DishListView(generics.ListCreateAPIView):
    serializer_class = DishSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        return Dish.objects.filter(is_available=True)

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return DishCreateUpdateSerializer
        return super().get_serializer_class()

    def perform_create(self, serializer):
        serializer.save(chef=self.request.user.chef_profile)

class DishDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Dish.objects.all()
    permission_classes = [permissions.IsAuthenticated, IsDishOwnerOrReadOnly]

    def get_serializer_class(self):
        if self.request.method in ['PUT', 'PATCH']:
            return DishCreateUpdateSerializer
        return DishSerializer

    def perform_destroy(self, instance):
        instance.is_available = False
        instance.save()